<template>
	<div>
		<div :class="wrapperClass" ref="wrapperRef">
			<div class="content-title">
				<div class="row-ac">
					<div class="flex-1"></div>
					<div class="language-celect row-ac cursor-pointer" @click="takeLanguage">
						<i class="iconfont icon-yuyan ml"></i>
						<div class="font-s-13" style="margin-left: 0.5rem;">{{ languageType }}</div>
					</div>
				</div>

				<div class="language-nav" v-if="languageModel">
					<div class="mt-10">
						<div class="language-item cursor-pointer" v-for="(item, index) in languageList" :key="index"
							@click="languageSelect(item)">
							<span>{{ item.name }}</span>
						</div>
					</div>
				</div>

				<div class="flex-1 row-a-j-fc">
					<h2>{{ languageType === 'English' ? englishTitle : turkeyTitle }}</h2>
				</div>
				<div class="flex-1 row-a-j-fc">
					<p>{{ languageType === 'English' ? englishContent : turkeyContent }}</p>
				</div>
			</div>
		</div>

		<!-- 图片部分 -->
		<div :style="girlBoxStyle">
			<div :style="girlStyle">
				<div :style="imageBoxStyle" class="position-relative">
					<img v-if="loadingState" :src="performerInfo.img" :style="imageStyle" @load="onImageLoad" />
					<div class="gallery-item_SubTitle">
						<span>
							{{ languageType == 'English' ? performerInfo.english_identity : performerInfo.turkey_identity }}
						</span>
					</div>
					<div class="elden-odeme cursor-pointer" @click.stop="takeContact">
						<span>{{ languageType == 'English' ? 'CLICK HERE' : 'TIKLA ARA' }}</span>
					</div>
					<div class="gradient-bar"></div>
					<div class="gallery-item_Content">
						<div class="gallery-item-title flex-1 row-ac-jc">
							{{ languageType == 'English' ? performerInfo.english_name : performerInfo.turkey_name }}
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		computed,
		nextTick
	} from 'vue'
	import {
		useRouter,
		useRoute
	} from 'vue-router'

	import {
		useLanguage
	} from '~/composables/useLanguage'

	const {
		languageType,
		setLanguage
	} = useLanguage()

	const router = useRouter()

	const {
		get,
		post
	} = useFetchApi()
	const route = useRoute()

	const wrapperClass = ref('content-wrapper')
	const wrapperRef = ref(null)

	const englishTitle = ref('FIRE WOMEN DETERMINE YOUR SEARCH')
	const turkeyTitle = ref('ATEŞLİ KADINLAR ARAMALARINIZI BEKLİYOR')
	const englishContent = ref('Online video chat, sexy beauties, 24-hour customer service')
	const turkeyContent = ref('Çevrimiçi görüntülü sohbet, seksi güzellikler, 7/24 müşteri hizmeti')

	const documentWidth = ref(0)
	const documentHeight = ref(0)
	const wrapperHeight = ref(0)

	const languageModel = ref(false)
	const languageList = ref([{
			id: 0,
			name: 'English'
		},
		{
			id: 1,
			name: 'Türkçe'
		}
	])

	const girlId = ref('')
	const performerInfo = ref({})
	const loadingState = ref(false)

	let resizeObserver = null

	/* ------------------------
	 * ✅ 1. 获取真实可视区域高度，兼容所有浏览器
	 * ------------------------ */
	const updateWindowSize = () => {
		if (typeof window !== 'undefined') {
			let width = 0
			let height = 0

			if (window.visualViewport) {
				width = window.visualViewport.width
				height = window.visualViewport.height
			} else {
				width = window.innerWidth
				height = window.innerHeight
			}

			// ✅ 同时取 innerHeight / clientHeight 最大值，防止导航栏遮挡
			const realHeight = Math.max(height, window.innerHeight, document.documentElement.clientHeight)
			documentWidth.value = width
			documentHeight.value = realHeight
		}
	}

	/* ------------------------
	 * ✅ 2. 计算 wrapper 高度
	 * ------------------------ */
	const updateWrapperHeight = async () => {
		await nextTick()
		wrapperHeight.value = wrapperRef.value ? wrapperRef.value.offsetHeight || 0 : 0
	}

	/* ------------------------
	 * ✅ 3. 监听 wrapper resize
	 * ------------------------ */
	const initObserver = () => {
		if (typeof ResizeObserver !== 'undefined' && wrapperRef.value) {
			resizeObserver = new ResizeObserver(() => {
				if (wrapperRef.value) {
					wrapperHeight.value = wrapperRef.value.offsetHeight || 0
				}
			})
			resizeObserver.observe(wrapperRef.value)
		}
	}

	/* ------------------------
	 * ✅ 4. 图片加载后更新高度
	 * ------------------------ */
	const onImageLoad = async () => {
		await updateWrapperHeight()
	}

	/* ------------------------
	 * ✅ 5. 监听窗口变化
	 * ------------------------ */
	const resizeHandler = async () => {
		updateWindowSize()
		await updateWrapperHeight()
	}

	/* ------------------------
	 * ✅ 6. 拉取数据
	 * ------------------------ */
	const performerData = async () => {
		try {
			const res = await get('/api/girl_profiles/' + girlId.value)
			if (res && res.code === 200) {
				performerInfo.value = res.data || {}
				loadingState.value = true
				await updateWrapperHeight()
			} else {
				console.log(res?.msg || 'fetch performer failed')
			}
		} catch (err) {
			console.error('Get performer failed:', err)
		}
	}

	const takeContact = async () => {
		try {
			const res = await post('/api/chat/create_session')
			if (res && res.code === 200) {
				const sessionId = res.data.session_id
				console.log('sessionId', sessionId);
				router.push({
					path: `/c/${sessionId}`
				})

			} else {
				console.log(res.msg || 'fetch performer failed')
			}
		} catch (err) {
			console.error('Get performer failed:', err)
		}
	}

	const takeLanguage = () => {
		languageModel.value = !languageModel.value
	}

	const languageSelect = async(item) => {
		setLanguage(item.name)
		languageModel.value = false
		localStorage.setItem('languageType', item.name) // ✅ 存储到本地
		await updateWrapperHeight()
	}
	onMounted(async () => {
		
		updateWindowSize()

		if (typeof window !== 'undefined') {
			if (window.innerWidth < 768) {
				wrapperClass.value = 'w-100 py-20 content-wrapper'
			}

			window.addEventListener('resize', resizeHandler)
			window.addEventListener('orientationchange', resizeHandler)

			if (window.visualViewport) {
				window.visualViewport.addEventListener('resize', resizeHandler)
			}
		}

		const savedLang = localStorage.getItem('languageType')
		if (savedLang) languageType.value = savedLang

		girlId.value = route.params.id
		await performerData()
		await updateWrapperHeight()
		initObserver()
	})

	onUnmounted(() => {
		if (typeof window !== 'undefined') {
			window.removeEventListener('resize', resizeHandler)
			window.removeEventListener('orientationchange', resizeHandler)
			if (window.visualViewport) {
				window.visualViewport.removeEventListener('resize', resizeHandler)
			}
		}
		if (resizeObserver) {
			resizeObserver.disconnect()
			resizeObserver = null
		}
	})

	/* ------------------------
	 * ✅ 9. 动态计算样式
	 * ------------------------ */
	const girlBoxStyle = computed(() => {
		let height = documentHeight.value - wrapperHeight.value
		if (height < 0) height = 0

		return {
			width: `${documentWidth.value}px`,
			height: `${height}px`,
			background: 'linear-gradient(135deg, #030d26 0%, #1a2a4a 100%)',
			paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 10px)', // ✅ 兼容 Android / iOS
			boxSizing: 'border-box',
			transition: 'height 0.3s ease'
		}
	})

	const girlStyle = computed(() => {
		let height = documentHeight.value - wrapperHeight.value
		if (height < 0) height = 0
		return {
			width: `${documentWidth.value}px`,
			height: `${height}px`,
			display: 'flex',
			justifyContent: 'center',
			alignItems: 'center',
			overflow: 'hidden'
		}
	})

	const imageBoxStyle = computed(() => {
		let maxHeight = documentHeight.value - wrapperHeight.value
		if (maxHeight < 0) maxHeight = 0
		return {
			border: '5px solid black',
			display: 'flex',
			justifyContent: 'center',
			alignItems: 'center',
			boxSizing: 'border-box',
			overflow: 'hidden',
			maxHeight: `${maxHeight}px`
		}
	})

	const imageStyle = computed(() => ({
		maxWidth: '100%',
		maxHeight: '100%',
		objectFit: 'contain',
		transition: 'all 0.3s ease'
	}))
</script>


<style>
</style>